package com.panopset.rdb;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * pojos as rdb case model.
 *
 * @author Karl Dinwiddie
 *
 */
public final class Table {

    /**
     * app.
     */
    public static final String DEFAULT_SCHEMA = "app";

    /**
     * Constructor provides table with default app schema.
     * @param tableName Table name.
     */
    public Table(final String tableName) {
        this(DEFAULT_SCHEMA, tableName);
    }

    /**
     * Most Panopset applications will have their own schema, but use the
     * default base url and rdb store, combined to make
     * <b>jdbc:h2:~/panopset/store</b>.
     *
     * @param tableSchema
     *            Schema name.
     * @param tableName
     *            Table name.
     */
    public Table(final String tableSchema, final String tableName) {
        schema = tableSchema.toUpperCase();
        name = tableName.toUpperCase();
    }

    /**
     * Primary key.
     */
    private Field primaryKey;

    /**
     *
     * @return Primary key.
     */
    public Field getPrimaryKey() {
        if (primaryKey == null) {
            primaryKey = new FieldString4096("key");
        }
        return primaryKey;
    }

    /**
     *
     * @param key
     *            Primary key.
     */
    public void setPrimaryKey(final Field key) {
        primaryKey = key;
    }

    /**
     * Fields.
     */
    private final List<Field> fields = new ArrayList<Field>();

    /**
     * @return Fields.
     */
    public List<Field> getFields() {
        return fields;
    }

    /**
     * @param field
     *            .
     */
    public void addField(final Field field) {
        fields.add(field);
    }

    /**
     * Schema.
     */
    private final String schema;

    /**
     * Table name.
     */
    private final String name;

    /**
     * @return Table schema.
     */
    public String getSchema() {
        return schema;
    }

    /**
     * @return Table name.
     */
    public String getName() {
        return name;
    }

    /**
     * @return schema.name
     */
    public String getSchemaDotName() {
        StringWriter sw = new StringWriter();
        sw.append(getSchema());
        sw.append(".");
        sw.append(getName());
        return sw.toString();
    }
}
